# -*- coding:utf-8 -*-


import os
import time
import SendKeys
import unittest, HTMLTestRunner
from time import sleep
import win32api, win32con
from pywinauto.application import Application
from extendScript.ChangeTestCase import TestCaseNumIMPL
from extendScript.RWExcleIMPL import ExcelImpl
from extendScript.DBAadaptor import DB_Excel
from extendScript.DBAadaptor import DB_MySQL


class SetPreProcessorTest():
    def __init__(self, listValue=None):
        # self.ei = ExcelImpl()
        self.gtd = GetTestData()
        self.listValue = self.gtd.get_onedata_value(listValue)
        self.startDEUPreProcessor(self.listValue)

    def startDEUPreProcessor(self, data):
        filePath = self.gtd.get_pz_data("PreProcessor")
        appt = Application()

        try:
            self.app = appt.connect(title_re="DEUModelBuilder")
            self.wfMain = self.app.DEUModelBuilder
        except Exception as e:
            self.app = appt.start(filePath)

            self.wfMain = self.app.DEUModelBuilder
            self.wfMain.Wait('ready')

            # ..........
            # 01、选择上球方式
            self.setProcessorType(self.wfMain, data[1], data[2])

            # 02、加载数据
            self.wfMain[u"添加"].Click()
            self.loadTestData(data[19])

            # print self.wfMain["LISTBOX2"].item_texts()
            # print self.wfMain['Edit3'].text_block()
            # print self.wfMain['Edit10'].text_block()

            # 03、加载LOD方案
            # print self.wfMain['ComboBox3'].ItemTexts()
            if data[3] in self.wfMain['ComboBox3'].ItemTexts():
                for index in self.wfMain['ComboBox3'].ItemTexts():
                    if index == data[3]:
                        self.wfMain['ComboBox3'].Select(index)
            else:
                self.wfMain['WindowsForms10.Window.8.app.0.2bf8098_r14_ad16'].Click()
                self.setLOD(data[9], data[3], int(data[4]), int(data[5]), int(data[6]), int(data[7]), int(data[8]))
                for index in self.wfMain['ComboBox3'].ItemTexts():
                    if index == data[3]:
                        self.wfMain['ComboBox3'].Select(index)

            # 04、设置投影方案
            self.setKJCK(self.wfMain, data[10], data[11], data[12], data[13], data[14])

            # 05、设置数据集编号
            self.setDataSetNO(self.wfMain, int(data[18]))

            # 06、设置输出路径
            self.wfMain[u'浏览'].Click()
            outputdata = os.getcwd() + "\\outputdata\\DataSet\\" + data[0] + "_" + str(int(data[18]))
            self.setOUTPutData(self.app[u'另存为'], outputdata)

            # 07、设置偏移XYZ值
            self.setXYZ(self.wfMain, data[15], data[16], data[17])

            # 08、点击开始
            self.wfMain[u"开始"].Click()

            while self.wfMain['Edit3'].IsEnabled() is False:
                sleep(2)

                # self.wfMain.Close()
                # .........

    def setProcessorType(self, winfrom, testData, testData1):  # 上球方式
        if testData == u'逐点上球':
            winfrom[u'逐点上球'].Click()
        if testData == u'共享上球':
            winfrom[u'共享上球'].Click()
        if testData1 == u'是':
            winfrom[u'多参考点'].Click()

    def loadTestData(self, loadpath):  # 加载数据

        openwin = self.app[u"打开"]
        openwin[u'Edit1'].SetEditText(loadpath)

        openwin[u'打开(&O)'].Click()

        try:
            openwin[u'打开(&O)'].Click()
        except:
            pass

        datalistwf = openwin[u"DirectUIHWND2"]
        (x, y) = ((datalistwf.Rectangle().right - datalistwf.Rectangle().left) / 2 + datalistwf.Rectangle().left,
                  (datalistwf.Rectangle().bottom - datalistwf.Rectangle().top) / 2 + datalistwf.Rectangle().top)

        win32api.SetCursorPos((x, y))

        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)

        SendKeys.SendKeys("^a")

        openwin[u'打开(&O)'].Click()

    def setLOD(self, youhua, lodName, lod1, lod2, lod3, lod4, lod5):

        self.app[u"FormLOD"][u'增加'].Click()

        formLodConfig = self.app['FormLODConfig']

        formLodConfig['Edit2'].SetEditText(lodName)

        if youhua == u"是":
            formLodConfig["BUTTON1"].Click()

        # LOD1
        formLodConfig['Edit7'].SetEditText(lod1)
        # LOD2
        formLodConfig['Edit6'].SetEditText(lod2)
        # LOD3
        formLodConfig['Edit5'].SetEditText(lod3)
        # LOD4
        formLodConfig['Edit4'].SetEditText(lod4)
        # LOD5
        formLodConfig['Edit3'].SetEditText(lod5)
        sleep(1)

        # 新增加
        formLodConfig[u'保存'].Click()
        self.app['FormMyMessageBox'][u'确定'].Click()

        # 关闭窗口
        formLodConfig['Static1'].Click()
        sleep(2)

    def setKJCK(self, winfrom, prj, ty, zyjx, eastset, northset):

        # 设置坐标系
        if prj == u"WGS84":
            winfrom['ComboBox2'].Select(0)
        if prj == u"北京54":
            winfrom['ComboBox2'].Select(1)
        if prj == u"西安80":
            winfrom['ComboBox2'].Select(2)
        if prj == u"哈尔滨":
            winfrom['ComboBox2'].Select(3)

        sleep(1)

        # 设置投影
        if ty == u"高斯":
            winfrom['ComboBox1'].Select(0)
        if ty == u"UTM":
            winfrom['ComboBox1'].Select(1)

        sleep(1)

        # 设置中央经线
        winfrom['Edit8'].SetEditText(zyjx)
        sleep(1)

        # 设置东偏
        winfrom['Edit10'].SetEditText(eastset)
        sleep(1)

        # 设置北偏
        winfrom['Edit9'].SetEditText(northset)
        sleep(1)

    def setXYZ(self, winfrom, x, y, z):
        # 设置X方向上偏移
        winfrom['Edit7'].SetEditText(x)
        sleep(1)

        # 设置Y方向上偏移
        winfrom['Edit5'].SetEditText(y)
        sleep(1)

        # 设置Z方向上偏移
        winfrom['Edit6'].SetEditText(z)
        sleep(1)

    def setOUTPutData(self, winfrom, outputdata):

        winfrom['Edit1'].SetEditText(outputdata)
        winfrom[u'保存(&S)'].Click()
        try:
            winfrom[u'保存(&S)'].Click()
        except Exception as e:
            pass

    def setDataSetNO(self, winfrom, strDataSetNO):
        winfrom['Edit3'].SetEditText(strDataSetNO)

    def getWinForm(self):
        return (self.app, self.wfMain, self.listValue)


class ExtractTestGui(unittest.TestCase):
    def setUp(self):
        # self.tcn = TestCaseNumIMPL()
        # self.svi = SetPreProcessorTest(listValue=self.tcn.getValue())
        # self.app, self.wfMain, self.listValue = self.svi.getWinForm()
        self.tcn = TestCaseNumIMPL()
        self.svi = SetPreProcessorTest(listValue=self.tcn.getValue())
        self.app, self.wfMain, self.listValue = self.svi.getWinForm()

    # def testinpath(self):  # 检测加载数据
    #     loadlistdata = []
    #     data = os.listdir(self.listValue[19])
    #     for filedir in data:
    #         if filedir.split(".")[1].lower() == "ive":
    #             loadlistdata.append(self.listValue[19] + "\\" + filedir)
    #     self.assertEqual(loadlistdata, self.wfMain["LISTBOX2"].item_texts())

    def testloadLOD(self):  # LOD检测
        datalod = self.listValue[3]
        self.assertEqual(datalod, self.wfMain["COMBOBOX3"].selected_text())

    def testprojection(self):  # 投影检测
        zuobiao = self.listValue[10]
        self.assertEqual(zuobiao, self.wfMain['ComboBox2'].selected_text())

    def testtouying(self):
        touying = self.listValue[11]
        self.assertEqual(touying, self.wfMain['ComboBox1'].selected_text())

    def testdong(self):
        dong = self.listValue[13]
        self.assertEqual(int(dong), int(self.wfMain['Edit10'].text_block()))

    def testbei(self):
        bei = self.listValue[14]
        self.assertEqual(int(bei), int(self.wfMain['Edit9'].text_block()))

    def testzhongyang(self):
        zhongyang = self.listValue[12]
        self.assertEqual(int(zhongyang), int(self.wfMain['Edit8'].text_block()))

    def testdataNumber(self):  # 数据集编号检测
        datano = self.listValue[18]
        self.assertEqual(int(datano), int(self.wfMain['Edit3'].text_block()))

    def testoutpath(self):  # 检测输出路径
        outputdata = os.getcwd() + "\\outputdata\\DataSet\\" + self.listValue[0] + "_" + str(int(self.listValue[18]))
        while self.wfMain[u'开始'].IsEnabled() is False:
            sleep(2)
        self.assertTrue(
            os.path.exists(outputdata + '.dscfg') and os.path.exists(outputdata + '.idx') and os.path.exists(
                outputdata + '_0.db'))

    # xyz------------------------------------------------------------
    def testx(self):  # xyz偏移
        xdata = str(round(self.listValue[15], 5))
        wfMainData = str(round(float(self.wfMain['Edit7'].text_block()), 5))
        self.assertEqual(xdata, wfMainData)

    def testy(self):
        ydata = str(round(self.listValue[16], 5))
        wfMainData = str(round(float(self.wfMain['Edit5'].text_block()), 5))
        self.assertEqual(ydata, wfMainData)

    def testz(self):
        zdata = str(round(self.listValue[17], 5))
        wfMainData = str(round(float(self.wfMain['Edit6'].text_block()), 5))
        self.assertEqual(zdata, wfMainData)

    def tearDown(self):
        pass


class initThisTester:
    def __init__(self):
        pass

    def delReportAndOutdata(self):
        print u"测试环境初始化，请稍后！"
        self.delReport()
        self.delOutdata()

    def delReport(self):
        self.delAllfolder(os.getcwd() + "\\ReportFile")

    def delOutdata(self):
        self.delAllfolder(os.getcwd() + "\\outputdata\\DataSet")

    def delAllfolder(self, filepath):
        for dfile in os.listdir(filepath):
            os.remove(filepath + "\\" + dfile)

    def closePreProcessor(self):
        try:
            app = Application().connect(title_re="DEUModelBuilder")
            wfMain = app.DEUModelBuilder

            sleep(1)

            wfMain['关闭'].Click()
            app['WindowsForms10.Window.8.app.0.2bf8098_r11_ad1']['确定'].Click()
        except Exception as e:
            print e

    def jltext_preprocessor(self):
        ei = ExcelImpl()
        tcn = TestCaseNumIMPL()
        tcn.setValue("TP1")

        inittter = initThisTester()
        # inittter.delReportAndOutdata()

        listcase = ei.getTestCaseByExcel(type="PreProcessor")
        for i in listcase:
            print "=" * 100
            print u"执行测试用例：" + i[0]
            print i

            SetPreProcessorTest(i[0])

            tcn.setValue(i[0])
            suite = unittest.makeSuite(ExtractTestGui)
            filename = os.getcwd() + "\\ReportFile\\" + i[0] + "_" + str(i[18]) + "_Report.html"
            fp = file(filename, 'wb')
            runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title=u'自动化测试报告',
                                                   description=u'自动化测试报告,测试用例' + i[0] + "_" + str(i[18]))
            runner.run(suite)
            inittter.closePreProcessor()

        tcn.setValue("TP1")

class GetTestData:
    def __init__(self):
        self.program = os.getcwd() + u'\\inputdata\\FilePath.xlsx'
        self.program_info = DB_Excel(self.program, u'FilePath').get_globe_dict()

    def get_pz_data(self, strOption):
        return self.program_info[strOption]

    def get_alldata_value(self):
        if self.program_info["dbsourcetype"] == 0:  # 0:excel 1:mysql
            return self.get_excel_data(os.getcwd() + "\\inputdata\\" + self.program_info["excel_PreProcessor"] + ".xlsx",
                                       self.program_info["excel_PreProcessor"])

        if self.program_info["dbsourcetype"] == 1:  # 0:excel 1:mysql
            return self.get_mysql_data(self.program_info["mysql_host"],
                                       self.program_info["mysql_username"], self.program_info["mysql_passwd"],
                                       self.program_info["mysql_dbname"], "PreProcessor")

    def get_onedata_value(self, strtestnum):
        if self.program_info["dbsourcetype"] == 0:  # 0:excel 1:mysql
            return self.get_excel_onedata(
                os.getcwd() + "\\inputdata\\" + self.program_info["excel_PreProcessor"] + ".xlsx",
                self.program_info["excel_PreProcessor"], strtestnum)

        if self.program_info["dbsourcetype"] == 1:  # 0:excel 1:mysql
            return self.get_mysql_onedata(self.program_info["mysql_host"],
                                          self.program_info["mysql_username"], self.program_info["mysql_passwd"],
                                          self.program_info["mysql_dbname"], "PreProcessor", strtestnum)

    def get_excel_data(self, excelpath, tablename):
        data_list = DB_Excel(excelpath, tablename).get_OneTestCase_row_RList()
        return data_list

    def get_mysql_data(self, host, username, passwd, dbname, tablename):
        data_list = DB_MySQL(host, username, passwd, dbname, tablename).get_OneTestCase_row_RList()
        return data_list

    def get_excel_program_info(self, excelpath):
        return DB_Excel(excelpath, 'FilePath').get_globe_dict()

    def get_mysql_program_info(self, host, username, passwd, dbname):
        return DB_MySQL(host, username, passwd, dbname, 'FilePath').get_globe_dict()

    def get_mysql_onedata(self, host, username, passwd, dbname, tablename, strtestnum):
        data_list = DB_MySQL(host, username, passwd, dbname, tablename)
        return data_list.get_OneTestCase_by_testNO(strtestnum)

    def get_excel_onedata(self, excelpath, tablename, strtestnum):
        data_list = DB_Excel(excelpath, tablename).get_OneTestCase_by_testNO(strtestnum)
        return data_list


if __name__ == '__main__':
    gtd = GetTestData()
    noTestcase = gtd.get_alldata_value()

    tcn = TestCaseNumIMPL()
    tcn.setValue("TC1")

    inittter = initThisTester()
    # inittter.delReportAndOutdata()

    for i in noTestcase:
        print "=" * 100
        print u"执行测试用例：" + i[0]
        print i

        SetPreProcessorTest(i[0])

        tcn.setValue(i[0])
        suite = unittest.makeSuite(ExtractTestGui)
        times = time.strftime("%Y_%m_%d", time.localtime())
        filename = os.getcwd() + "\\ReportFile\\" + i[0] + times + "_" + str(i[18]) + "_Report.html"
        fp = file(filename, 'wb')
        runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title=u'自动化测试报告',
                                               description=u'自动化测试报告,测试用例' + i[0] + "_" + str(i[18]))
        runner.run(suite)
        inittter.closePreProcessor()

    tcn.setValue("TP1")
